﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Wattpad;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;

namespace BlogTruyen
{
    public partial class StoryDetails : PhoneApplicationPage
    {
        Models.Story Data;
        ApplicationBarIconButton pinButton = new ApplicationBarIconButton(new Uri("/Assets/Icons/dark/appbar.pin.png", UriKind.Relative))
        {
            Text = "ghim",
            //IsEnabled = false
        };
        ApplicationBarIconButton unPinButton = new ApplicationBarIconButton(new Uri("/Assets/Icons/dark/appbar.pin.remove.png", UriKind.Relative))
        {
            Text = "bỏ ghim",
            //IsEnabled = false
        };
        string imageFolder = @"\Shared\ShellContent\"; 
        string isolateCoverPath;
        private string tileUrl;
        private bool IsTileExist
        {
            get
            {
                return CheckIfTileExist(tileUrl);
            }
        }

        public StoryDetails()
        {
            InitializeComponent();

            Data = new Models.Story();
            DataContext = Data;
        }

        private void CreateAppBar()
        {
            ApplicationBar = new ApplicationBar();
            pinButton.Click += pinButton_Click;
            unPinButton.Click += unPinButton_Click;
            if (IsTileExist)
            {
                ApplicationBar.Buttons.Add(unPinButton);
            }
            else {
                ApplicationBar.Buttons.Add(pinButton);
            }
                
        }

        private void unPinButton_Click(object sender, EventArgs e)
        {
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(
                x => x.NavigationUri.ToString() == tileUrl
            );
            if (TileToFind != null)
            {
                string filePath = System.IO.Path.Combine(imageFolder, isolateCoverPath);
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    myIsolatedStorage.DeleteFile(filePath);
                }
                TileToFind.Delete();
                CreateAppBar();
                MessageBox.Show("Đã gỡ bỏ khỏi màn hình chính!", "Thông báo", MessageBoxButton.OK);
            }
        }

        private bool CheckIfTileExist(string query)
        {
            // Create secondary tile, if it is not already present
            // Look to see if the tile already exists and if so, don't try to create again.
            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(
                x => x.NavigationUri.ToString()==query
            );

            // Create the tile if it is not already pinned
            if (TileToFind == null)
            {
                return false;
            }
            return true;
        }

        void pinButton_Click(object sender, EventArgs e)
        {
            string filePath = System.IO.Path.Combine(imageFolder, isolateCoverPath);
            //IsolatedStorage_Utility.Save<byte[]>(filePath, IsolatedStorage_Utility.ImageToByteArray((BitmapSource)imgCover.Source));
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(filePath);

                WriteableBitmap wb = new WriteableBitmap((BitmapSource)imgCover.Source);

                // Encode WriteableBitmap object to a JPEG stream. 
                Extensions.SaveJpeg(wb, fileStream, 336, 336, 0, 100);

                fileStream.Close();
            }


            StandardTileData NewTileData = new StandardTileData
            {
                BackgroundImage = new Uri(String.Format(@"isostore:{0}", filePath), UriKind.Absolute),
                Title = Data.title,
                //BackTitle = "Blog Truyện",
                //BackBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative)
            };
            

            // Create the tile and pin it to Start. This will cause a navigation to Start and a deactivation of our application.
            
            ShellTile.Create(new Uri(tileUrl, UriKind.Relative), NewTileData);
            CreateAppBar();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!Data.isLoaded)
            {
                Data.title = NavigationContext.QueryString["title"];
                var webClient = API.GetWebClient();
                webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
                webClient.DownloadStringAsync(new Uri(string.Format("http://blogtruyen.com{0}", NavigationContext.QueryString["url"]), UriKind.Absolute));
                API.SetProgressIndicator(LayoutRoot, true, "Loading...");
            }
        }

        void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (API.CheckWebClient(e))
            {
                Data.LoadHtml(e.Result);
                //pinButton.IsEnabled = true;
                isolateCoverPath = NavigationContext.QueryString["url"].Replace("/", "_") + ".png";
                tileUrl = String.Format("/StoryDetails.xaml?url={0}&title={1}", NavigationContext.QueryString["url"], NavigationContext.QueryString["title"]);
                CreateAppBar();
            }
            API.SetProgressIndicator(LayoutRoot, false);
        }

        private void Chapter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var chapter = ((FrameworkElement)sender).DataContext as Models.Chapter;
            chapter.viewed = true;
            NavigationService.Navigate(new Uri(string.Format("/{2}?url={0}&title={1}", chapter.url, Data.title + " " + chapter.name, Models.Config.GetValue("readtype")), UriKind.Relative));
        }
    }
}